#include "taskmanager.h"
#include "memorypool.h"
#include <QDateTime>
// 静态成员变量初始化
int TaskManager::nextTaskId = 0;

TaskManager::TaskManager() {}

TaskManager::~TaskManager() {}

TaskInfo TaskManager::createTask(size_t memSize)
{
    TaskInfo task;
    task.taskId = nextTaskId++; // 先赋值，后自增
    task.memSize = memSize;
    task.allocatedPtr = HashBucket::useMemory(memSize);
    task.poolIdx = HashBucket::getPoolIdxBySize(memSize);
    task.timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    return task;
}
void TaskManager::addTask(const TaskInfo& task)
{
    m_taskList.push_back(task);
    // 避免频繁更新UI，而是每次按下分配按钮时更新
    // emit taskListChanged();
}
// 批量更新
void TaskManager::batchUpdate()
{
    emit taskBatchAdded();
}
void TaskManager::removeTask(int taskId)
{
    for (auto it = m_taskList.begin(); it != m_taskList.end(); ++it)
    {
        if (it->taskId == taskId)
        {
            HashBucket::freeMemory(it->allocatedPtr, it->memSize);
            m_taskList.erase(it);
            break;
        }
    }
    emit taskRemoved(taskId);
}
void TaskManager::clearTaskList()
{
    for (auto& task : m_taskList)
    {
        HashBucket::freeMemory(task.allocatedPtr, task.memSize);
    }
    m_taskList.clear();
    nextTaskId = 0;
    emit taskListCleared();
}
std::vector<TaskInfo> TaskManager::getTaskList() const
{
    return m_taskList;
}
